
package com.eyedog.video.videolist;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.eyedog.library.base.BaseRecyclerAdapter;
import com.eyedog.uilibrary.lists.BaseListFragment;
import com.eyedog.video.R;
import com.eyedog.video.adv.AdvInstance;
import com.eyedog.video.constant.Constants;
import com.eyedog.video.entity.ADVEntity;
import com.eyedog.video.entity.AdvVideoEntity;
import com.eyedog.video.videoad.VideoDetailAdActivity;

import java.util.List;

/**
 * created by jw200 at 2019/3/29 21:20
 **/
public class VideoListFragment extends BaseListFragment
        implements constract.IView, View.OnClickListener {
    static final int TYPE_ADV = 0x01;

    static final int TYPE_VIDEO = 0x02;

    VideoListAdapter mAdapter;

    List<AdvVideoEntity> mEntities;

    VideoPresenter presenter;

    int categoryId = Constants.Category_Empty;

    String keywords;

    ADVEntity mAdvEntity;

    SearchWindow mSearchWindow;

    public static Bundle createVideoListBundle(int categoryId) {
        Bundle data = new Bundle();
        data.putInt("CategoryId", categoryId);
        return data;
    }

    public static Bundle createVideoListBundle(String keywords) {
        Bundle data = new Bundle();
        data.putString("KeyWords", keywords);
        return data;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tvSearch.setOnClickListener(this);
        etSearch.addTextChangedListener(textWatcher);
        etSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mSearchWindow == null) {
                    mSearchWindow = new SearchWindow(getActivity());
                    mSearchWindow.window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            if(etSearch != null && !getActivity().isFinishing()){
                                etSearch.clearFocus();
                            }
                        }
                    });
                }
                mSearchWindow.window().showAsDropDown(etSearch,0,0);
            }
        });
    }

    @Override
    protected void onRefresh() {
        if (categoryId >= 0) {
            presenter.showVideoList(mCurrentPage, categoryId);
        } else if (categoryId == Constants.Category_RecommendId) {
            presenter.showRecommendVideoList(mCurrentPage);
        } else if (categoryId == Constants.Category_NewId) {
            presenter.showNewestVideoList(mCurrentPage);
        } else if (!TextUtils.isEmpty(keywords)) {
            presenter.showVideoList(mCurrentPage, keywords);
        } else {
            presenter.showVideoList(mCurrentPage, 0);
        }
    }

    @Override
    protected void onLoadMore() {
        onRefresh();
    }

    @Override
    protected void onRecyclerCreated(RecyclerView recyclerView) {
        mCurrentPage = 1;
        Bundle args = getArguments();
        int categoryId = Constants.Category_Empty;
        String keywords = null;
        if (args != null) {
            categoryId = args.getInt("CategoryId", Constants.Category_Empty);
            keywords = args.getString("KeyWords");
        }
        presenter = new VideoPresenter(new VideoModel(), this);
        mAdapter = new VideoListAdapter(getActivity());
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        recyclerView.setAdapter(mAdapter);
        this.categoryId = categoryId;
        this.keywords = keywords;
        if (categoryId == Constants.Category_RecommendId) {
            mAdvEntity = AdvInstance.getInstance().getRecommendAdv();
        } else {
            mAdvEntity = AdvInstance.getInstance().getVideoListAdv();
        }
        if (mAdvEntity != null) {
            ivAdv.setVisibility(View.VISIBLE);
            ivAdv.setOnClickListener(this);
            Glide.with(getActivity()).load(mAdvEntity.img).into(ivAdv);
        } else {
            ivAdv.setVisibility(View.GONE);
        }
        onRefresh();
    }

    @Override
    public void showVideoList(final List<AdvVideoEntity> videoEntities) {
        this.mEntities = videoEntities;
        if (recyclerView != null && mAdapter != null) {
            recyclerView.post(new Runnable() {
                @Override
                public void run() {
                    recyclerView.refreshComplete();
                    recyclerView.loadMoreComplete();
                    mAdapter.add(videoEntities);
                }
            });
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_video_headeradv: {
                if (mAdvEntity != null) {
                    ADVEntity advEntity = mAdvEntity;
                    if (advEntity != null && !TextUtils.isEmpty(advEntity.url)) {
                        Uri uri = Uri.parse(advEntity.url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                    }
                }
            }
            break;
            case R.id.tv_search: {
                String keywords = etSearch.getText().toString().trim();
                Bundle data = VideoListActivity.createVideoListBundle(keywords, keywords);
                Intent intent = new Intent(getActivity(), VideoListActivity.class);
                intent.putExtras(data);
                startActivity(intent);
            }
            break;
        }
    }

    class BaseHolder extends RecyclerView.ViewHolder {
        public BaseHolder(View itemView) {
            super(itemView);
        }
    }

    class VideoHolder extends BaseHolder {

        TextView tvDesc;

        ImageView ivThumb;

        LinearLayout layout;

        public VideoHolder(@NonNull View itemView) {
            super(itemView);
            tvDesc = (TextView) itemView.findViewById(R.id.tv_desc);
            ivThumb = (ImageView) itemView.findViewById(R.id.iv_thumb);
            layout = (LinearLayout) itemView.findViewById(R.id.ll_videolist_layout);
            layout.setOnClickListener(videoClickListener);
        }
    }

    class AdvHolder extends BaseHolder {
        ImageView ivAdv;

        View layout;

        public AdvHolder(View itemView) {
            super(itemView);
            ivAdv = (ImageView) itemView.findViewById(R.id.iv_adv);
            layout = itemView.findViewById(R.id.fl_advlayout);
            layout.setOnClickListener(advClickListener);
        }
    }

    class VideoListAdapter extends BaseRecyclerAdapter<AdvVideoEntity, BaseHolder> {

        public VideoListAdapter(Context context) {
            super(context);
        }

        @NonNull
        @Override
        public BaseHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int type) {
            if (getItemCount() > 0) {
                int itemType = type;
                if (itemType == TYPE_ADV) {
                    View layout = LayoutInflater.from(getContext())
                            .inflate(R.layout.layout_item_adv, viewGroup, false);
                    return new AdvHolder(layout);
                } else {
                    View layout = LayoutInflater.from(getContext())
                            .inflate(R.layout.layout_videolist, viewGroup, false);
                    return new VideoHolder(layout);
                }
            }
            return null;
        }

        @Override
        public int getItemViewType(int position) {
            if (getItemCount() > 0) {
                AdvVideoEntity advVideoEntity = getItem(position);
                if (advVideoEntity.advEntity != null) {
                    return TYPE_ADV;
                } else {
                    return TYPE_VIDEO;
                }
            }
            return super.getItemViewType(position);
        }

        @Override
        public void onBindViewHolder(@NonNull BaseHolder videoHolder, int i) {
            if (getItemCount() > 0) {
                int itemType = getItemViewType(i);
                AdvVideoEntity videoEntity = getItem(i);
                if (itemType == TYPE_VIDEO) {
                    VideoHolder holder = (VideoHolder) videoHolder;
                    if (!TextUtils.isEmpty(videoEntity.getVod_name())) {
                        holder.tvDesc.setVisibility(View.VISIBLE);
                        holder.tvDesc.setText(videoEntity.getVod_name());
                    } else {
                        holder.tvDesc.setVisibility(View.GONE);
                        // holder.tvDesc.setText(videoEntity.getVod_name());
                    }
                    // holder.tvDesc.setText(videoEntity.getDesc());
                    if (!TextUtils.isEmpty(videoEntity.getVod_pic())) {
                        Glide.with(getContext()).load(videoEntity.getVod_pic())
                                .into(holder.ivThumb);
                    }
                    holder.layout.setTag(videoEntity);
                } else if (itemType == TYPE_ADV) {
                    AdvHolder holder = (AdvHolder) videoHolder;
                    ADVEntity advEntity = videoEntity.advEntity;
                    if (advEntity != null) {
                        Glide.with(getContext()).load(advEntity.img).into(holder.ivAdv);
                    }
                    holder.layout.setTag(advEntity);
                }
            }
        }
    }

    View.OnClickListener videoClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Object tag = v.getTag();
            if (tag != null && tag instanceof AdvVideoEntity) {
                Bundle data = VideoDetailAdActivity.createBundle(
                        ((AdvVideoEntity) tag).getVod_url(), ((AdvVideoEntity) tag).getVod_pic(),
                        ((AdvVideoEntity) tag).getVod_name());
                Intent intent = new Intent(getActivity(), VideoDetailAdActivity.class);
                intent.putExtras(data);
                startActivity(intent);
            }
        }
    };

    View.OnClickListener advClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Object tag = view.getTag();
            if (tag != null && tag instanceof ADVEntity) {
                ADVEntity advEntity = ((ADVEntity) tag);
                if (advEntity != null && !TextUtils.isEmpty(advEntity.url)) {
                    Uri uri = Uri.parse(advEntity.url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
            }
        }
    };

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable != null && editable.length() > 0) {
                tvSearch.setEnabled(true);
            } else {
                tvSearch.setEnabled(false);
            }
        }
    };
}
